package com.pj.project4sp;

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.opencsv.exceptions.CsvValidationException;
import org.kohsuke.github.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class Util {
    private static final String REPO_NAME = "baba511/ipyouxuan"; // GitHub仓库名
    private static final String FILE_PATH = "/yxip/result/ip.txt"; // 本地文件路径
    private static final String GITHUB_TOKEN = "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"; // GitHub访问令牌
    private static final String COMMIT_MESSAGE = "1111"; // 提交消息
    private static final String BRANCH = "main"; // 目标分支

    //启动批处理
    public  void bat(){
        List<String> batchFilePath = Arrays.asList(
                "/yxip/45102.sh");

        for (String bat:batchFilePath) {
            listBat(bat);
        }
    }
    //保存cvs
    public  void cvs(){
        // 定义CSV文件路径

        // 定义多个CSV文件的路径
        List<String> csvFiles = Arrays.asList(
//                "C:\\Users\\user\\Desktop\\nodigyue\\result\\AS16509-0-0.csv",
//                "C:\\Users\\user\\Desktop\\nodigyue\\result\\AS0-0-HKG.csv",
//                "C:\\Users\\user\\Desktop\\nodigyue\\result\\AS0-0-ICN.csv",
//                "C:\\Users\\user\\Desktop\\nodigyue\\result\\AS0-0-LAX.csv",
//               "C:\\Users\\user\\Desktop\\nodigyue\\result\\AS0-0-NRT.csv",
//                "C:\\Users\\user\\Desktop\\nodigyue\\result\\AS0-0-SIN.csv",
                "/yxip/result/AS45102-0-0.csv"
        );
        // 要读取的行号，从0开始计数（比如读取第2行和第4行）
        int[] linesToRead = {1,2,3,4,5,6,7,8,9,10};
        List<String[]> no = new ArrayList<>();
        for (String csvFile :csvFiles) {
            // 读取并输出指定的行
            List<String[]>  ss = readSpecificLines(csvFile, linesToRead);
            no.addAll(ss);
        }
        // 输出读取到的行
        for (String[] values : no) {
            for (String value : values) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
        // 将所有CSV数据保存到一个新的CSV文件中
        String outputCsvFile = "/yxip/result/AAAA.csv";
        writeCSVFile(outputCsvFile, no);
        System.out.println("All data has been written to " + outputCsvFile);
    }
    //保存到txt
    public  void txt(){
        // 定义多个CSV文件的路径
        List<String> csvFiles = Arrays.asList(
                "/yxip/result/AAAA.csv"
        );
        // 存储所有目标列数据的集合
        List<String> columnData = new ArrayList<>();
//        Map map =new HashMap<>();
        // 指定要提取的列索引（例如，提取第二列，索引为1）
        int columnIndex1 = 0;
        int columnIndex = 1;
        int columnIndex4 = 4;
        for (String csvFile : csvFiles) {
            List<String>  data = readCSVColumn(csvFile, columnIndex1,columnIndex,columnIndex4);
            columnData.addAll(data);

        }
        for (String value : columnData) {
            System.out.println(value);
//            System.out.println(columnData.get(3)+":"+columnData.get(4)+"#"+columnData.get(5));
        }
        String fileName = "/yxip/result/ip.txt";
        //win
//        userHome(fileName,columnData);
//        liunx
        LiunxText(fileName,columnData);
    }
    //上传ghb
    public  void ghb(){
        try {
            // 连接到GitHub
            GitHub github = new GitHubBuilder().withOAuthToken(GITHUB_TOKEN).build();
            // 获取指定仓库
            GHRepository repo = github.getRepository(REPO_NAME);
            // 检查文件是否已经存在
            String filePathInRepo = FILE_PATH.substring(FILE_PATH.lastIndexOf("/") + 1);
            boolean fileExists = false;
            try {
                repo.getFileContent(filePathInRepo, BRANCH);
                fileExists = true;
            } catch (IOException e) {
                // 文件不存在，将会创建新文件
            }
            // 读取文件内容
            File file = new File(FILE_PATH);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] fileContent = new byte[(int) file.length()];
            fileInputStream.read(fileContent);
            fileInputStream.close();
            String content = new String(fileContent);

            // 创建或更新文件
            GHContentBuilder contentBuilder = repo.createContent();
            if (fileExists) {
                GHContentUpdateResponse response = repo.getFileContent(filePathInRepo, BRANCH)
                        .update(content, COMMIT_MESSAGE, BRANCH);
                System.out.println("File updated successfully: " + response.getCommit().getSHA1());
            } else {
                contentBuilder.content(content)
                        .path(filePathInRepo)
                        .branch(BRANCH)
                        .message(COMMIT_MESSAGE)
                        .commit();
                System.out.println("File created successfully!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<String[]> readSpecificLines(String csvFile, int[] linesToRead) {
        String line = "";
        String csvSplitBy = ",";
        // 使用列表来暂存指定行的数据
        List<String[]> selectedLines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
            int currentLineNum = 0;
            int nextLineIndex = 0;

            while ((line = br.readLine()) != null) {
                if (nextLineIndex < linesToRead.length && currentLineNum == linesToRead[nextLineIndex]) {
                    String[] values = line.split(csvSplitBy);
                    selectedLines.add(values);
                    nextLineIndex++;
                }
                currentLineNum++;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return selectedLines;
    }
    // 将数据写入CSV文件
    public static void writeCSVFile(String csvFile, List<String[]> data) {
        try (CSVWriter writer = new CSVWriter(new FileWriter(csvFile))) {
            for (String[] row : data) {
                writer.writeNext(row);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static  List<String> readCSVColumn(String csvFile, int columnIndex1,int columnIndex,int columnIndex4) {
//        List<String[]> csvData = new ArrayList<>();
        List<String> columnData = new ArrayList<>();
//        Map  columnData =new HashMap<>();
        try (CSVReader reader = new CSVReader(new FileReader(csvFile))) {
            String[] line;
            while ((line = reader.readNext()) != null) {
                // 检查列索引是否在范围内
                if (columnIndex < line.length) {
                    columnData.add(line[columnIndex1]+":"+line[columnIndex]+"#"+line[columnIndex4]);
                }
            }
        } catch (IOException | CsvValidationException e) {
            e.printStackTrace();
        }
        return  columnData;
    }
    public static void userHome(String fileName,List<String> content) {
        // 获取用户的主目录
        String userHome = System.getProperty("user.home");
        // 获取桌面路径
        String desktopPath = userHome + File.separator + "Desktop";
        String filePath = desktopPath + File.separator + fileName;
        // 创建并写入文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (String row : content) {
                writer.write(row+ System.lineSeparator());
            }
            System.out.println("File written successfully on the Desktop.");
        } catch (IOException e) {
            System.err.println("An error occurred while writing the file: " + e.getMessage());
        }
    }

    public static void listBat(String batchFilePath){
        try {
            // 指定批处理文件的路径
//            String batchFilePath = "C:\\Users\\user\\Desktop\\aaa.bat";
            // 创建ProcessBuilder对象
            ProcessBuilder processBuilder = new ProcessBuilder(batchFilePath);
            // 设置工作目录（可选）
            // 如果你的批处理文件依赖于特定的工作目录，请设置工作目录
            processBuilder.directory(new File("/yxip"));
            // 启动进程
            Process process = processBuilder.start();
            // 读取进程的标准输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }
            // 等待进程执行结束
            int exitCode = process.waitFor();
            // 打印进程的退出码
            System.out.println("批处理文件执行完成，退出码：" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void LiunxText(String filePath,List<String> content){
        // 指定文件路径和文件名
//        String filePath = "/path/to/your/file.txt";

        try {
            // 创建文件对象
            File file = new File(filePath);

            // 如果文件不存在，则创建新文件
            if (file.createNewFile()) {
                System.out.println("文件已创建：" + file.getAbsolutePath());
            } else {
                System.out.println("文件已存在，无需创建。");
            }
            // 可选：向文件写入内容
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                for (String row : content) {
                    writer.write(row+ System.lineSeparator());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
